package pers.qianyu.module.logging.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.scheduling.annotation.*;
import org.springframework.stereotype.*;
import pers.qianyu.module.core.comm.*;
import pers.qianyu.module.core.domain.logging.converter.*;
import pers.qianyu.module.core.domain.logging.dto.*;
import pers.qianyu.module.core.domain.logging.entity.*;
import pers.qianyu.module.core.domain.logging.query.*;
import pers.qianyu.module.core.domain.logging.vo.*;
import pers.qianyu.module.core.util.*;
import pers.qianyu.module.logging.dao.*;
import pers.qianyu.module.logging.service.*;

import java.util.*;

/**
 * @author mizzle rain
 * @date 2020-10-30 15:03
 */
@Service("requestLogService")
public class RequestLogServiceImpl implements RequestLogService {
    @Autowired
    private RequestLogDao requestLogDao;
    @Autowired
    private RequestLogConverter requestLogConverter;

    @Override
    @Async("loggingServiceExecutor")
    public void insertAsync(RequestLogDTO requestLogDTO) {
        RequestLogPO requestLogPO = requestLogConverter.convertToPO(requestLogDTO);
        requestLogDao.insert(requestLogPO);
    }

    @Override
    public Pagination<RequestLogVO> query(RequestLogQuery query) {
        Page<RequestLogPO> page = new Page<>(query.getPage(), query.getLimit());
        RequestLogPO requestLogPO = requestLogConverter.convertToPO(query);
        QueryWrapper<RequestLogPO> wrapper = new QueryWrapper<>(requestLogPO);
        String startTimeStr = query.getStartTime();
        String endTimeStr = query.getEndTime();
        if (Objects.nonNull(startTimeStr)) {
            long startTime = DateTimeUtil.toMillis(startTimeStr);
            long endTime = Objects.isNull(endTimeStr) ? System.currentTimeMillis() : DateTimeUtil.toMillis(endTimeStr);
            wrapper.between("create_time", startTime, endTime);
        }
        wrapper.orderByDesc("update_time");
        Page<RequestLogPO> requestLogPOPage = requestLogDao.selectPage(page, wrapper);
        return requestLogConverter.convertToPagination(requestLogPOPage);
    }
}
